package com.jiuzhe.commercial.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.util.Base64;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public final class BitmapUtils {

	/**
     * 一种节省内存的加载大图片的方式。
     * @param context
     * @param resId
     * @return
     */
	public static Bitmap readBitmap(Context context, int resId) {
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		// 获取资源图片
		InputStream is = context.getResources().openRawResource(resId);
		Bitmap bitmap = BitmapFactory.decodeStream(is, null, opt);
		try {
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bitmap;
	}

	/**
	 * 读取本地图片
	 * @param imgPath
	 * @return
	 */
	 public static Bitmap readBitmap(String imgPath) {
	        try {
	            return BitmapFactory.decodeFile(imgPath);
	        } catch (Exception e) {
	            return null;  
	        }  
	}  
	 
	
	/**
	 *  将bitmap转换成base64字符串 　　 　　
	 *  @param bitmap 　　
	 *  @return base64 字符串 　　
	 */
	public static String bitmaptoString(Bitmap bitmap, int bitmapQuality) {
		String string = null;
		try {
			// 将Bitmap转换成字符串
			ByteArrayOutputStream bStream = new ByteArrayOutputStream();
			bitmap.compress(CompressFormat.PNG, bitmapQuality, bStream);
			byte[] bytes = bStream.toByteArray();
			string = Base64.encodeToString(bytes, Base64.DEFAULT);

			bStream.flush();
			bStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return string;
	}
	
	/**
	 * 判断是否存在sd卡
	 * @return
	 */
	 public static boolean ExistSDCard() {
		  if (android.os.Environment.getExternalStorageState().equals(
		    android.os.Environment.MEDIA_MOUNTED)) {
		   return true;
		  } else
		   return false;
		 }

}
